import { useEffect, useState, useCallback } from "react";
import { useLiveQuery } from "dexie-react-hooks";
import { db } from "./database";
import { setUserConfig, getUserConfigData, removeUserConfig } from "./helpers";

// 使用用户配置的Hook
export function useUserConfig(userId: string, configType: string) {
  const [config, setConfig] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 使用Dexie的实时查询
  const dexieConfig = useLiveQuery(
    () => db.userConfigs.where({ userId, configType }).first(),
    [userId, configType],
  );

  useEffect(() => {
    const loadConfig = async () => {
      try {
        setLoading(true);
        setError(null);

        if (dexieConfig) {
          setConfig(dexieConfig.configData);
        } else {
          const configData = await getUserConfigData(userId, configType);
          setConfig(configData);
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : "加载配置失败");
      } finally {
        setLoading(false);
      }
    };

    loadConfig();
  }, [userId, configType, dexieConfig]);

  const saveConfig = useCallback(
    async (configData: any) => {
      try {
        setError(null);
        const success = await setUserConfig(userId, configType, configData);
        if (success) {
          setConfig(configData);
        }
        return success;
      } catch (err) {
        setError(err instanceof Error ? err.message : "保存配置失败");
        return false;
      }
    },
    [userId, configType],
  );

  const deleteConfig = useCallback(async () => {
    try {
      setError(null);
      const success = await removeUserConfig(userId, configType);
      if (success) {
        setConfig(null);
      }
      return success;
    } catch (err) {
      setError(err instanceof Error ? err.message : "删除配置失败");
      return false;
    }
  }, [userId, configType]);

  return {
    config,
    loading,
    error,
    saveConfig,
    deleteConfig,
  };
}

// 使用用户所有配置的Hook
export function useAllUserConfigs(userId: string) {
  const configs = useLiveQuery(
    () => db.userConfigs.where("userId").equals(userId).toArray(),
    [userId],
  );

  const clearAllConfigs = useCallback(async () => {
    try {
      await db.userConfigs.where("userId").equals(userId).delete();
      return true;
    } catch (error) {
      console.error("清空用户配置失败:", error);
      return false;
    }
  }, [userId]);

  return {
    configs: configs || [],
    loading: configs === undefined,
    clearAllConfigs,
  };
}
